package com.mjp.learn.multi.juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * reentrantLock 的构造函数可以通过传入参数设置这个锁是否为公平锁
 */
public class Demo03 implements Runnable{
    //通过构造函数指定reentrantLock是否为公平锁
    public static final ReentrantLock fairLock = new ReentrantLock(true);

    @Override
    public void run() {
        while(true){
            try{
                fairLock.lock();
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName()+": get lock");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                fairLock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        Demo03 thread = new Demo03();
        Thread t1 = new Thread(thread);
        Thread t2 = new Thread(thread);
        t1.start();
        t2.start();
    }
}
